package com.psp.stockgroup.controller;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.psp.stockgroup.domain.StockMyGroup;
import com.psp.stockgroup.service.IStockMyGroupService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 股票分组Controller
 *
 * @author tiger
 * @date 2022-09-24
 */
@RestController
@RequestMapping("/eye/stockGroup")
public class StockMyGroupController extends BaseController {
    @Autowired
    private IStockMyGroupService stockMyGroupService;

    /**
     * 查询股票分组列表
     */
    @PreAuthorize("@ss.hasPermi('eye:stockGroup:list')")
    @GetMapping("/list")
    public TableDataInfo list(StockMyGroup stockMyGroup) {
        startPage();
        List<StockMyGroup> list = stockMyGroupService.selectStockMyGroupList(stockMyGroup);
        return getDataTable(list);
    }

    @GetMapping("/listOption")
    public AjaxResult listOption() {
        List<Map<String, Object>> list = stockMyGroupService.selectStockMyGroupOption();
        return AjaxResult.success(list);
    }

    /**
     * 获取股票分组详细信息
     */
    @PreAuthorize("@ss.hasPermi('eye:stockGroup:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(stockMyGroupService.selectStockMyGroupById(id));
    }

    /**
     * 新增股票分组
     */
    @PreAuthorize("@ss.hasPermi('eye:stockGroup:add')")
    @Log(title = "股票分组", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StockMyGroup stockMyGroup) {
        return toAjax(stockMyGroupService.insertStockMyGroup(stockMyGroup));
    }

    /**
     * 修改股票分组
     */
    @PreAuthorize("@ss.hasPermi('eye:stockGroup:edit')")
    @Log(title = "股票分组", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StockMyGroup stockMyGroup) {
        return toAjax(stockMyGroupService.updateStockMyGroup(stockMyGroup));
    }

    /**
     * 批量修改股票分组
     */
    @PutMapping("/batchUpdateStockMyGroup")
    public AjaxResult batchUpdateStockMyGroup(@RequestBody List<StockMyGroup> stockMyGroupList) {
        stockMyGroupService.batchUpdateStockMyGroup(stockMyGroupList);
        return AjaxResult.success("拖动成功!");
    }

    /**
     * 删除股票分组
     */
    @PreAuthorize("@ss.hasPermi('eye:stockGroup:remove')")
    @Log(title = "股票分组", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(stockMyGroupService.deleteStockMyGroupByIds(ids));
    }

    /**
     * 导出股票分组列表
     */
    @Log(title = "股票分组", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StockMyGroup stockMyGroup) {
        List<StockMyGroup> list = stockMyGroupService.selectStockMyGroupList(stockMyGroup);
        ExcelUtil<StockMyGroup> util = new ExcelUtil<StockMyGroup>(StockMyGroup.class);
        util.exportExcel(response, list, "股票分组数据");
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<StockMyGroup> util = new ExcelUtil<>(StockMyGroup.class);
        util.importTemplateExcel(response, "股票模板");
    }

    /**
     * 导入股票分组
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<StockMyGroup> util = new ExcelUtil<>(StockMyGroup.class);
        List<StockMyGroup> exportList = util.importExcel(file.getInputStream());
        List<StockMyGroup> updateList = new ArrayList<>();
        List<StockMyGroup> addList = new ArrayList<>();
        List<StockMyGroup> deleteList = new ArrayList<>();

        List<StockMyGroup> dbList = stockMyGroupService.selectStockMyGroupList(new StockMyGroup());

        // 导入的数据在数据库中存在股票编码则更新,不存在则新增
        exportList.forEach(n -> {
            // 确定唯一值的判定
            Optional<StockMyGroup> optional = dbList.stream().filter(b -> n.getId().equals(b.getId())).findFirst();
            if (optional.isPresent()) {
                // 更新项
                optional.get().setName(n.getName());
                optional.get().setSortNum(n.getSortNum());
                updateList.add(optional.get());
            } else {
                addList.add(n);
            }
        });
        // 查找待删除记录
        dbList.forEach(n -> {
            if (exportList.stream().noneMatch(b -> n.getId().equals(b.getId()))) {
                deleteList.add(n);
            }
        });
        if (addList.size() > 0) {
            stockMyGroupService.batchInsertStockMyGroup(addList);
        }
        if (updateList.size() > 0) {
            stockMyGroupService.batchUpdateStockMyGroup(updateList);
        }
        if (deleteList.size() > 0) {
            stockMyGroupService.deleteStockMyGroupByIds(deleteList.stream().map(StockMyGroup::getId).toArray(String[]::new));
        }
        return AjaxResult.success();

    }

}
